import Vue from 'vue'
import VueRouter from 'vue-router'
// 推荐页
import Rec from '../pages/recommend/Main.vue'
import RecMain from '../pages/recommend/Main.vue'
import RecMainDe from '../pages/recommend/MainBannerDetail.vue'
import RecTopic from '../pages/recommend/topic.vue'
import RecSort from '../pages/recommend/sort.vue'
import RecGoods from '../pages/recommend/goods.vue'
import RecMine from '../pages/recommend/mine.vue'
// 百科页
import Enc from '../pages/encyclopedias/Main.vue'
import EncDe from '../pages/encyclopedias/MainDetail.vue'
//登陆页
import Login from '../pages/public/login.vue'
// 注册页
import Reg from '../pages/public/reg.vue'



// 404页
import NotFound from '../pages/public/404.vue'
import axios from 'axios'

Vue.use(VueRouter)

const routes = [
  // path和name都要是字符
  // 登陆
  {
    path:'/login',
    name: 'Login',
    component: Login
  },
  // 注册
  {
    path:'/reg',
    name: 'Reg',
    component: Reg
  },
  // 推荐页
  {
    // 首页
    path: '/rec',
    // name: 'Rec',
    // 父重定向默认到子首页
    redirect: '/rec/main',
  },
  // 子页
  // 子首页
  {
    path: '/rec/main',
    name: 'RecMain',
    component: RecMain
  },
  // 子首页的详情页
  {
    path: '/rec/main/:_id',
    name: 'RecMainDetail',
    component: RecMainDe,
    // 这里的meta字段用来标识是否显示详情页
    meta:{path:'detail'}
  },
  // 子话题页
  {
    path: '/rec/topic',
    name: 'RecTopic',
    component: RecTopic
  },
  // 子分类页
  {
    path: '/rec/sort',
    name: 'RecSort',
    component: RecSort
  },
  // 子购物车
  {
    path: '/rec/goods',
    name: 'RecGoods',
    component: RecGoods
  },
  // 子个人
  {
    path: '/rec/mine',
    name: 'RecMine',
    component: RecMine
  },


  // 百科页
  {
    path: '/enc',
    name: 'Enc',
    component: Enc
  },
  // 百科详情
  {
    path: '/enc/:_id',
    name: 'EncDe',
    component: EncDe,
    meta:{path:'detail'}
  },


  // 默认页是推荐的首页
  {
    path: '/',
    // 重定向
    redirect: '/rec/main'
  },
  
  {
    // 404
    path: '*',
    name: 'NotFound',
    component: NotFound
  }

]

const router = new VueRouter({
  // 使用history模式
  mode: 'history',
  routes
})

// 路由的前置守卫
// 未登陆的需要登陆之后才能访问
router.beforeEach((to, from, next) => {
  // 这里只校验token
  // 组件的数据还是需要组件自己去读取
  let path = to.path;

  if (path.includes('/login') || path.includes('/reg')) {
    next();
  } else {
    axios({
      url: 'public/isToken',
    }).then(
      res => {
        // 没有登陆就跳转到登陆
        if (res.err === 2 && !to.path.includes('/login')) {
          console.log("守卫", res);
          next(`/login?path=${to.fullPath}`);
        } else {
          next();
        }

      }
    )
  }


})


export default router